package org.jeecg.modules.xl.kuaidi100.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackData;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.SignUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.kuaidi100.entity.XlKuaidi100Logitrace;
import org.jeecg.modules.xl.kuaidi100.mapper.XlKuaidi100LogitraceMapper;
import org.jeecg.modules.xl.kuaidi100.service.IXlKuaidi100LogitraceService;
import org.jeecg.modules.xl.logicmana.entity.XlCustomerLogisticPackage;
import org.jeecg.modules.xl.logicmana.service.IXlCustomerLogisticPackageService;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.service.IXlCustomerOrdeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: xl_kuaidi100_logitrace
 * @Author: jeecg-boot
 * @Date:   2024-12-09
 * @Version: V1.0
 */
@Service
public class XlKuaidi100LogitraceServiceImpl extends ServiceImpl<XlKuaidi100LogitraceMapper, XlKuaidi100Logitrace> implements IXlKuaidi100LogitraceService {

    public List<QueryTrackData> queryHasCheckTrace(String logi_com_code, String logi_code ){
        return baseMapper.queryHasCheckTrace(logi_com_code,logi_code);
    }
    String key = "apCDGXjp8152";
    String customer = "3E163C1F545E1D6C38EC8DABE13293B3";
    String secret ="c28bd653d6bc405288bb31ffe799e741";
    String userid =  "c28bd653d6bc405288bb31ffe799e741";
    @Autowired
    private XlLogUtil xlLogUtil ;

    @Autowired
    private IXlCustomerLogisticPackageService packageService;

    @Autowired
    private IXlCustomerOrdeService ordeService;


    /**
     *
     * @param comp 物流公司编码，必填
     * @param logisticorder 快递单号，必填
     * @param phone 收、寄件人 号码，非必填
     */
//    @IgnoreAuth
    public Result<List<QueryTrackData>> queryTrack(String comp, String logisticorder , String phone,String orderCode) throws Exception {
        Result<List<QueryTrackData>> resultT = new Result<>();
        if("chengshipeisong".equals(comp)||"CSPS".equals(comp)){
            List<QueryTrackData>  ss = new ArrayList<>();
            QueryTrackData temp =new QueryTrackData();
            temp.setTime(DateUtil.now());
            temp.setContext("该订单是城市配送订单，请等待司机送货上门!!");
            ss.add(temp);
            return Result.ok(ss);
        }
        XlCustomerOrde targetOrder =   ordeService.getOneByCode(orderCode);
        //先查库，如果有就直接返回，只有签收的才会落库
        //另外，如果 订单已经签收了，也是直接返回了，不管数据库有没有轨迹
        List<QueryTrackData> queryTrackDataList = queryHasCheckTrace(comp,logisticorder);
        if(ObjectUtil.isNotEmpty(queryTrackDataList)){
            return Result.ok(queryTrackDataList);
        }
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        queryTrackParam.setCom(comp);
        queryTrackParam.setNum(logisticorder);
        queryTrackParam.setPhone(phone);
        queryTrackParam.setResultv2("4");
        String param = new Gson().toJson(queryTrackParam);

        queryTrackReq.setParam(param);
        queryTrackReq.setCustomer(customer);
        queryTrackReq.setSign(SignUtils.querySign(param, key, customer));

        IBaseClient baseClient = new QueryTrack();
        //System.out.println(baseClient.execute(queryTrackReq));
        HttpResult result = baseClient.execute(queryTrackReq);
        QueryTrackResp queryTrackResp = new Gson().fromJson(result.getBody(), QueryTrackResp.class);

        String qianshouTime = "";
        if(ObjectUtil.isNotEmpty(queryTrackResp.getData())){
            List<XlKuaidi100Logitrace> xlKuaidi100Logitraces = new ArrayList<>();
            //用户已签收 ｜｜ 或者 疑难件，是快递的最终状态
            if ("1".equals(queryTrackResp.getIscheck())||queryTrackResp.getState().startsWith("2")) {
                for (QueryTrackData queryTrackData : queryTrackResp.getData()) {
                    if ("签收".equals(queryTrackData.getStatus())) {
                        qianshouTime = queryTrackData.getFtime();
                    }
                    XlKuaidi100Logitrace tracetemp = new XlKuaidi100Logitrace();
                    //tracetemp.setLogiCode(xlCustomerLogisticTemp.getOrderCode());
                    //bugfix 物流轨迹保存错误
                    tracetemp.setLogiCode(logisticorder);
                    tracetemp.setLogiComCode(queryTrackResp.getCom());
                    tracetemp.setStatuscode(queryTrackData.getStatusCode());
                    tracetemp.setStatus(queryTrackData.getStatus());
                    tracetemp.setTime(queryTrackData.getTime());
                    tracetemp.setFtime(queryTrackData.getFtime());
                    tracetemp.setContext(queryTrackData.getContext());
                    try {
                        super.save(tracetemp);
                    }catch (DuplicateKeyException e){
                        continue;
                    }

                    xlKuaidi100Logitraces.add(tracetemp);
                }
                //需要将物流轨迹落库
                //iXlKuaidi100LogitraceService.saveOrUpdateBatch(xlKuaidi100Logitraces);
                //自动更新订单为状态为 已签收
                autoSetOrderStatusToReceived(orderCode, logisticorder);
            }
        }

        return Result.ok(queryTrackResp.getData());
    }


    private void autoSetOrderStatusToReceived(String orderCode,String logiCode){
        //自动更新订单为状态为 已签收
        UpdateWrapper<XlCustomerOrde> ordeUpdateWrapper = new UpdateWrapper<>();
        ordeUpdateWrapper.set("order_status", "已收货")
                .eq("order_code", orderCode)
                .eq("order_status", "待收货");
        ordeService.update(ordeUpdateWrapper);
        //自动更新物流为状态为 已签收
        UpdateWrapper<XlCustomerLogisticPackage> xlCustomerLogisticPackageUpdateWrapper = new UpdateWrapper<>();
        xlCustomerLogisticPackageUpdateWrapper.set("is_check", "1")
                .set("update_time",DateUtil.date())
                .eq("logi_order", logiCode);
        packageService.update(xlCustomerLogisticPackageUpdateWrapper);
        xlLogUtil.insertLog(orderCode, "签收", "系统抓取物流轨迹签收", new Date(), "待收货", "已收货");
    }
}
